/*
 * Copyright 2013 Sigurd Randoll <srandoll@digiway.de>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server;

import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
import de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage;
import de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorageFactory;
import de.digiway.rapidbreeze.server.infrastructure.objectstorage.migration.ObjectStorageMigrate;
import de.digiway.rapidbreeze.server.migrate.V001_DataInit;
import de.digiway.rapidbreeze.shared.rest.ResourceLocation;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sigurd Randoll <srandoll@digiway.de>
 */
public class RapidBreezeServer {

    private HttpServer server;
    public static final String HOST = "localhost";
    private static final Logger LOG = Logger.getLogger(RapidBreezeServer.class.getName());

    public static void main(String[] args) {
        RapidBreezeServer server = new RapidBreezeServer();
        server.migrate();
        server.start();
    }

    private void start() {
        try {
            URI uri = new URI("http", null, HOST, ResourceLocation.PORT, "/", null, null);
            LOG.log(Level.INFO, "Starting up HTTP-Server on: {0}", uri);
            server = HttpServerFactory.create(uri);
            server.start();
        } catch (URISyntaxException | IOException | IllegalArgumentException ex) {
            LOG.log(Level.SEVERE, "Server error", ex);
        }
    }

    public void stop() {
        if (server != null) {
            server.stop(0);
        }
    }

    private void migrate() {
        ObjectStorageMigrate.Builder builder = new ObjectStorageMigrate.Builder();
        builder.migrationPackage(V001_DataInit.class.getPackage().getName());
        builder.objectStorage(ObjectStorageFactory.getInstance());
        ObjectStorageMigrate migrate = builder.build();

        try {
            migrate.migrate();
        } catch (Exception ex) {
            throw new IllegalStateException("Cannot initialize or migrate " + ObjectStorage.class.getSimpleName(), ex);
        }
    }
}
